package com.upc.feedish.ui.dashboard;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.upc.feedish.R;
import com.upc.feedish.utils.DataBaseController;
import com.upc.feedish.utils.MyTools;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

public class DashboardFragment extends Fragment {

//    private DashboardViewModel dashboardViewModel;
//    private FragmentDashboardBinding binding;
    private View root;
    Uri imageUri;
    String picBase64;
    Handler handlerS;
    Handler handlerF;
    String name;
    ImageView imageView;
    TextView tv_name;
    TextView tv_appetite;
//    TextView tv_temperature;
    Button camera;
    Button picture;
    DataBaseController dataBaseController;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(root==null){
            root=inflater.inflate(R.layout.fragment_dashboard,container,false);
        }
        dataBaseController=new DataBaseController();
        imageView=(ImageView)root.findViewById(R.id.imageViewF);
        tv_name=root.findViewById(R.id.nameF);
        tv_appetite=root.findViewById(R.id.appetiteF);
//        tv_temperature=root.findViewById(R.id.temperatureF);

        handlerS = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                HashMap<String,Object> map= (HashMap<String, Object>) msg.obj;
                tv_name.setText("种类："+map.get("name"));
                tv_appetite.setText("百科："+map.get("appetite")+"");
//                tv_temperature.setText("适宜温度："+map.get("temperature")+"℃");
            };
        };
        handlerF = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                HashMap<String,Object> map= (HashMap<String, Object>) msg.obj;
                tv_name.setText("种类："+map.get("name"));
                tv_appetite.setText("百科："+map.get("appetite")+"");
//                tv_temperature.setText("适宜温度："+map.get("temperature")+"");
            };
        };
        camera = root.findViewById(R.id.opencameraF);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 关键：新建相机的 Intent
                startActivityForResult(intent, 1); // 加载相机 Activity
            }
        });
        picture = root.findViewById(R.id.openlocalpicF);

        picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开本地相册
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //设定结果返回
                startActivityForResult(i, 2);
            }
        });
        return root;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bitmap bm=null;
        try{
            //自己拍摄
            if (requestCode == 1 && resultCode == RESULT_OK) {
                bm = (Bitmap) data.getExtras().get("data");
                imageView.setImageBitmap(bm);
            }
            //从本地相册选择
            else if (requestCode == 2 && resultCode == RESULT_OK) {
                Uri selectedImage = data.getData();
                bm = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(selectedImage));
                imageView.setImageBitmap(bm);
            }
            picBase64=MyTools.bitmapToBase64(bm);
            final Map<String,String> params = new HashMap<String,String>();
            params.put("image", picBase64);
            params.put("id_card_side","front");
            new Thread(new Runnable() {//创建子线程
                public void run() {
                    try {
                        String myAssess = MyTools.getAuth();
                        String strUrlPath = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal?access_token="+myAssess;
                        String strResult=MyTools.submitPostData(strUrlPath,params, "utf-8");
                        JSONObject jsonObject=new JSONObject(strResult);
                        JSONArray jsonArray= (JSONArray) jsonObject.get("result");
                        JSONObject jsonObject1= (JSONObject) jsonArray.get(0);
                        String name= (String) jsonObject1.get("name");

                        SharedPreferences sp = getActivity().getSharedPreferences("data",MODE_PRIVATE);
                        String token= sp.getString("token","");
                        HashMap<String,Object> map=new HashMap<>() ;
                        try {
                            map= dataBaseController.getAdvice(token,name);
                            map.put("name",name);
                            Message msg = Message.obtain();
                            msg.obj = map;//传递的数据
                            handlerS.sendMessage(msg);
                        }catch (Exception e){
                            e.printStackTrace();
                            map.put("name",name);
                            map.put("appetite","未找到");
                            map.put("temperature","未找到");
                            Message msg = Message.obtain();
                            msg.obj = map;        //传递的数据
                            handlerF.sendMessage(msg);
                        }


//                        if(map.get("appetite").equals("")){
//                            map.put("name",name);
//                            Message msg = Message.obtain();
//                            msg.obj = map;        //传递的数据
//                            handler.sendMessage(msg);
//                        }
//                        Message msg = Message.obtain();
//                        msg.obj = map;//传递的数据
//                        handlerS.sendMessage(msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();//启动子线程
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}